import ComponentBase from "../../BASE/ComponentBase";


const {ccclass, property} = cc._decorator;

@ccclass
export default class Countdown extends ComponentBase
{
    thetime:number=30//设定倒计时时间
    isstop:boolean=false//计时是否停止
    nowtime:number//倒计时时间显示

    start(){
        this.settime(30)
        // this.starttimer()测试30秒倒计时

        this.node.active=true
    }

    starttimer()
    {
        let startime=Date.now()//获取开始倒计时的时间戳
        //倒计时回调
        let schedulecallback= () =>
        {
            let tnowtime=Date.now()//当前回调的时间戳
            let nowtime=this.thetime-(Math.floor((tnowtime-startime)/1000+0.1))//计算当前剩余的时间并处理精度,设备的1秒精度在-0.1-0.1左右
            this.nowtime=nowtime//当前倒计时时间
            this.node.children[0].getComponent(cc.Label).string=this.nowtime+""
            console.log(nowtime)
            // console.log(this.thetime,nowtime,(tnowtime-startime)/1000)测试
            if(nowtime<=0)
            {
                this.timeend()
                this.stoptimer()//时间到点停止
            }
            if(this.isstop)//是否结束
            {
                this.isstop=false//停止后置为false,便于下次倒计时的开启
                if(nowtime>0) this.timeend()//如果是中途停止的调用这个把数据清除掉
                this.unschedule(schedulecallback)//停止
            }
        }
        if(this.thetime>0) this.schedule(schedulecallback,1)//开始倒计时
    }


    settime(time:number)//设定倒计时时间
    {
        this.thetime=time
    }

    timeend()//倒计时结束
    {
        console.log("结束")
        this.thetime=0
        this.nowtime=0
    }

    stoptimer()//停止,可以在倒计时还在运行的时候调用,调用后倒计时停止
    {
        this.isstop=true
    }


 

}